import puppeteer from 'puppeteer';
import * as fs from 'fs';
import * as path from 'path';

const launchBrowser = async (config?) => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    args: ['--no-default-browser-check'],
    // ignoreDefaultArgs: ['--enable-automation'],
    // devtools: true
    ...config,
  });
  return browser;
};

// 打开浏览器任务
const mainTask = async (browser, article) => {
  // 打开页面
  const url =
    'https://creator.xiaohongshu.com/publish/publish?from=homepage&target=image&source=official&openFilePicker=true';

  //   隔离上下文
  const context = await browser.createBrowserContext();

  // 设置登录身份
  article.user.cookies.forEach((cookie) => {
    context.setCookie(cookie);
  });

  const page = await context.newPage(url);
  await page.goto(url);

  await upload(page, article.fileList);
  await inputTitle(page, article);
  await inputContent(page, article);

  return await submit(page);
};

// 上传至小红书
const upload = async (page, imgs) => {
  const input_uploadPic = await page.waitForSelector('.upload-input');

  // 第一张图当作封面
  const firstItem = imgs.shift();
  input_uploadPic.uploadFile(firstItem.absolutePath);

  // 上传其他图片
  const input_uploadPic2 = await page.waitForSelector('.top input');
  imgs.forEach((img) => {
    input_uploadPic2.uploadFile(img.absolutePath);
  });
  return null;
};
// 写入标题
const inputTitle = async (page, article) => {
  const titleInput = await page.waitForSelector('input.d-text');
  return titleInput.type(article.title);
};
// 写入内容
const inputContent = async (page, article) => {
  const contentInput = await page.waitForSelector('div.ql-editor');
  return contentInput.type(article.content);
};
const submit = async (page) => {
  const publishBtn = await page.waitForSelector('button.publishBtn');

  return new Promise((resolve) => {
    setTimeout(() => {
      publishBtn.click(publishBtn);
      resolve(0);
    }, 6000);
  });
};
const close = async (browser) => {
  setTimeout(() => {
    browser.close();
  }, 1500);
};

export { launchBrowser, mainTask, close };
